package message

import (
	"encoding/binary"
	"gitee.com/zhongguo168a/gocodes/datax"
	"gitee.com/zhongguo168a/gocodes/datax/binaryx"
	"gitee.com/zhongguo168a/gocodes/myx/errorx"
	"io"
)

// 服务器推送消息
type SyncCreate struct {
	Key           string
	SerializeMode int8
	Data          []byte
}

func (msg *SyncCreate) Unpack(reader io.Reader) error {
	if data, err := binaryx.ReadUTF(reader, binary.LittleEndian); err != nil {
		return errorx.Wrap(err, "read Key")
	} else {
		msg.Key = data
	}
	if err := binary.Read(reader, binary.LittleEndian, &msg.SerializeMode); err != nil {
		return errorx.Wrap(err, "read SerializeMode")
	}
	if data, err := binaryx.ReadBytes(reader, binary.LittleEndian); err != nil {
		return errorx.Wrap(err, "read Rows")
	} else {
		msg.Data = data
	}

	return nil
}
func (msg *SyncCreate) PackageLen() int {
	// PushTag + Key + SerializeMode + Rows
	return 1 + (2 + len(msg.Key)) + 1 + (2 + len(msg.Data))
}

//封包方法(压缩数据)
func (msg *SyncCreate) Pack(writer io.Writer) error {
	if err := binary.Write(writer, binary.LittleEndian, int16(msg.PackageLen())); err != nil {
		return errorx.Wrap(err, "write PackageLen", datax.M{"PackageLen": msg.PackageLen()})
	}
	// tag data
	if err := binary.Write(writer, binary.LittleEndian, int8(PushTag_SyncCreate)); err != nil {
		return errorx.Wrap(err, "write PushTag", datax.M{"PushTag": int8(PushTag_SyncCreate)})
	}

	if err := binaryx.WriteUTF(writer, binary.LittleEndian, msg.Key); err != nil {
		return errorx.Wrap(err, "write Key", datax.M{"Key": msg.Key})
	}

	if err := binary.Write(writer, binary.LittleEndian, msg.SerializeMode); err != nil {
		return errorx.Wrap(err, "write SerializeMode", datax.M{"SerializeMode": msg.SerializeMode})
	}
	if err := binaryx.WriteBytes(writer, binary.LittleEndian, msg.Data); err != nil {
		return errorx.Wrap(err, "write Rows", datax.M{"Rows": msg.Data})
	}
	return nil
}
